import { useEffect, useState } from 'react';

import { Button, Space, Form, Row, Col, Input, Table, Image, Modal } from 'antd';
import { PAGINATION_CONFIG } from '@/constants';
import type { QueryBigNormalListParams, BigNormal } from './services';
import { BigNormalStatus, queryList, bindingUser } from './services'
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import { history } from '@umijs/max'
import ChargeModal, { ChargeModalProps } from './components/ChargeModal'
import BindingModal from './components/BindingModal'
import { jump2target } from '@/utils/common';

const BigNormalPage: React.FC = () => {
  const [searchForm] = Form.useForm<QueryBigNormalListParams>()
  const [searchParams, setSearchParams] = useState<QueryBigNormalListParams>({
    pageNum: 1, pageSize: 10,
  })
  const list = useRequest(() => queryList(searchParams), {
    refreshDeps: [searchParams],
  })
  const { runAsync: unbinding } = useRequest(bindingUser, {manual: true})
  const [chargeModalProps, setChargeModalProps] = useState<ChargeModalProps>()
  const [bindingModalOpen, setBindingModalOpen] = useState(false)

  const openChargeModal = (record: BigNormal) => {
    setChargeModalProps({userId: record.userId, balance: record.balance})
  }

  const openChargeList = (record: BigNormal) => {
    jump2target(`/bigRecharge?loginPhone=${record.telephone}`, {needRefresh: true})
  }

  const onChargeModalCancel = (refresh: boolean) => {
    if (refresh) list.refresh()
    setChargeModalProps(undefined)
  }

  const openBindingModal = () => {
    setBindingModalOpen(true)
  }

  const closeBindingModal = (refresh: boolean) => {
    if (refresh) list.refresh()
    setBindingModalOpen(false)
  }

  const confirmUnbinding = (record: BigNormal) => {
    Modal.confirm({
      title: `确定解绑用户 ${record.nickname} 吗？`,
      content: `解绑后将自动回收剩余授信额度（${record.balance}元）。`,
      onOk: () => unbinding({userId: record.userId, status: 2}).then(list.refresh),
    })
  }

  const onFinish = (formValues: any) => {
    setSearchParams({
      ...searchParams,
      loginPhone: formValues.loginPhone,
      pageNum: 1,
    })
  }

  const columns: ColumnsType<BigNormal> = [
    {
      title: '用户头像',
      dataIndex: 'userImg',
      width: 100,
      render: val => val && <Image style={{width: 40, height: 40}} src={val} />,
    },
    {
      title: '用户昵称',
      dataIndex: 'nickname',
      width: 100,
      render: val => val || '--',
    },
    {
      title: '手机号',
      dataIndex: 'telephone',
      width: 140,
      render: val => val || '--',
    },
    {
      title: '授信余额(元)',
      dataIndex: 'balance',
      width: 130,
      render: val => val || 0,
    },
    {
      title: '用户状态',
      dataIndex: 'userStatus',
      width: 80,
      render: val => {
        if (val === 1) {
          return '正常'
        }
        if (val === 2) {
          return '平台禁用中'
        }
        if (val === 3) {
          return '平台已删除'
        }
        return '--'
      },
    },
    {
      title: '操作',
      key: 'operations',
      width: 160,
      fixed: 'right',
      render: (_, record) => {
        return <Space>
          <a onClick={() => openChargeModal(record)}>授信</a>
          <a onClick={() => openChargeList(record)}>授信记录</a>
          <a onClick={() => confirmUnbinding(record)}>解绑</a>
        </Space>
      }
    },
  ]

  useEffect(() => {
    const refresh = () => {
      list.refresh()
    }
    window.addEventListener('refreshBigNormalList', refresh)
    return () => {
      window.removeEventListener('refreshBigNormalList', refresh)
    }
  }, []);
  
  return (
    <div className='container'>
      <div className="card search-card">
        <div className="toolbar">
          <Space>
            <Button type='primary' onClick={() => openBindingModal()}>绑定用户</Button>
          </Space>
        </div>
        <div className="form-area">
          <Form name='searchBigNormalForm' form={searchForm} onFinish={onFinish}>
            <Row gutter={[20, 20]}>
              <Col span={6}>
                <Form.Item label='用户手机号' name='loginPhone'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={list.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className="card content-card">
        <Table<BigNormal>
          rowKey='telephone'
          loading={list.loading}
          dataSource={list.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: list.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </div>
      <ChargeModal
        {...chargeModalProps}
        onCancel={onChargeModalCancel}
      />
      <BindingModal
        open={bindingModalOpen}
        onCancel={closeBindingModal}
      />
    </div>
  );
};

export default BigNormalPage;
